package com.vincent.sciinfo.interceptor;

import com.vincent.sciinfo.exception.TokenExpiredException;
import com.vincent.sciinfo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JWTInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {

        //获取header中的token以及对应的claims信息
        String token = request.getHeader("token");
        //是否通过
        Boolean isAllowPass = true;
        //如果token信息为空
        if (token == null) {
            isAllowPass = false;
        } else {
            //获取到token中的信息 并看是否过期
            if (JwtUtils.getClaimByToken(token) == null) {
                throw new TokenExpiredException("您好，您的用户信息已过期！请重新登录。");
            }
        }
        return isAllowPass;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
